package com.customization.unionpay.market.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.customization.unionpay.market.dao.MarketActivityEventDao;
import com.customization.unionpay.market.util.FormDataUtils;
import com.customization.unionpay.market.util.FormUtil;
import com.customization.unionpay.market.dao.ClearFundDetailDao;
import com.customization.unionpay.market.service.ClearFundDetailService;
import com.customization.unionpay.market.util.FormDataUtil;
import com.customization.unionpay.market.util.PropUtils;
import weaver.backup.logging.Logger;
import weaver.backup.logging.LoggerFactory;
import weaver.file.ftp.FTPFileUtil;
import weaver.general.Util;
import weaver.hrm.User;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

public class ClearFundDetailServiceImpl implements ClearFundDetailService {

    public Logger log = LoggerFactory.getLogger(ClearFundDetailServiceImpl.class);

    @Override
    public String getDailyDetailByDate(String date, User user) {
        try {

//            FTPFileUtil fileUtil = new FTPFileUtil(FtpConfig.CLEAR_FUND_DETAIL_FTP_HOST,
//                    FtpConfig.CLEAR_FUND_DETAIL_FTP_PORT,
//                    FtpConfig.CLEAR_FUND_DETAIL_FTP_USER,
//                    FtpConfig.CLEAR_FUND_DETAIL_FTP_PWD);

//            FTPFileUtil fileUtil = new FTPFileUtil(FtpConfig.CLEAR_FUND_DETAIL_FTP_HOST,
//                    FtpConfig.CLEAR_FUND_DETAIL_FTP_PORT,
//                    FtpConfig.CLEAR_FUND_DETAIL_FTP_USER,
//                    FtpConfig.CLEAR_FUND_DETAIL_FTP_PWD);
//            InputStream inputStream = null;
//            inputStream = fileUtil.downloadFile(FtpConfig.CLEAR_FUND_DETAIL_FTP_PATH+date+"/",
//                    FtpConfig.CLEAR_FUND_DETAIL_FTP_FILE_NAME_PREFIX+date+
//                            FtpConfig.CLEAR_FUND_DETAIL_FTP_FILE_NAME_SUFFIX);
//            log.info("host"+FtpConfig.CLEAR_FUND_DETAIL_FTP_HOST);
//            log.info("port"+FtpConfig.CLEAR_FUND_DETAIL_FTP_PORT);
//            log.info("user"+FtpConfig.CLEAR_FUND_DETAIL_FTP_USER);
//            log.info("pwd"+FtpConfig.CLEAR_FUND_DETAIL_FTP_PWD);
//            log.info("path"+FtpConfig.CLEAR_FUND_DETAIL_FTP_PATH+date+"/");
//            log.info("fileName"+FtpConfig.CLEAR_FUND_DETAIL_FTP_FILE_NAME_PREFIX
//                    +date+FtpConfig.CLEAR_FUND_DETAIL_FTP_FILE_NAME_SUFFIX);

            String username = PropUtils.BB_LOG.getPropValue("marketSubject", "ftp_username");
            //密码
            String password = PropUtils.BB_LOG.getPropValue("marketSubject", "ftp_password");
            //地址
            String ip = PropUtils.BB_LOG.getPropValue("marketSubject", "ftp_ip");
            //端口号
            int port = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "ftp_port"));
            //编码
            String fileCode = PropUtils.BB_LOG.getPropValue("marketSubject", "ftp_file_code");

            FTPFileUtil fileUtil = new FTPFileUtil(ip,port,username,password);
            InputStream inputStream = null;

            String path = PropUtils.BB_LOG.getPropValue("marketSubject", "ftp_path");
            //密码
            String prefix = PropUtils.BB_LOG.getPropValue("marketSubject", "ftp_prefix");
            //地址
            String suffix = PropUtils.BB_LOG.getPropValue("marketSubject", "ftp_suffix");

            inputStream = fileUtil.downloadFile(path+date+"/", prefix+date+suffix);
//            InputStream inputStream = new FileInputStream(new File("C:\\Users\\wu\\Desktop\\MarketingFund_20240725"));
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, fileCode));
            String text = null;
            List<String> content = new ArrayList<>();
            while ((text = reader.readLine()) != null) {
                content.add(text);
            }
            dealDailyDetailData(content, user);
            return "success";
        } catch (Exception e) {
            log.error("读取文件出错" + e, e);
        }
        return "fail";
    }

    /**
     * 处理清除资金明细数据
     *
     * @param datas
     * @return
     */
    public boolean dealDailyDetailData(List<String> datas, User user) {
        try {
            // 清算资金汇总台账表单id
            int formId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "clearing_fund_summary_ledger_form_id"));
            log.info("formId == >" + formId);
            // 清算资金汇总台账模块id
            int formmodeId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "clearing_fund_summary_ledger_formmode_id"));
            log.info("formmodeId == >" + formmodeId);

            com.customization.unionpay.market.service.impl.ClearFundDetailsButtonServiceImpl clearFundDetailsButtonService = new ClearFundDetailsButtonServiceImpl();

            /**
             * 数据的格式为： 数据存在倒数第一个不存在的情况 且前三行不是有效数据
             * 预算授权码,业务类型,平台启动日期,清算日期,清算金额,活动结项标志,出账机构(积分)
             * 2024032215042500197381,新积分(普通),20240322,20240411,7126500.00,否
             * 2023081114174000155151,积分（普通）_,20230810,20240411,-9.00,
             */
            for (int i = 3; i < datas.size(); i++) {
                String[] dataArr = datas.get(i).split(",");
                //授权码
                String sqm = dataArr[0];
                //正则判断授权码是否全为0
                if (sqm.matches("^0+$")) {
                    continue;
                }
                //业务类型
                String ywlx = dataArr[1];
                //平台启动日期
                String ptqdrq = String.format("%s-%s-%s",
                        dataArr[2].substring(0, 4),
                        dataArr[2].substring(4, 6),
                        dataArr[2].substring(6, 8));
                //清算日期
                String qsrq = String.format("%s-%s-%s",
                        dataArr[3].substring(0, 4),
                        dataArr[3].substring(4, 6),
                        dataArr[3].substring(6, 8));
                //清算金额
                String qsje = dataArr[4];
                //活动结束标志
                String hdjsbs = "否";
                if (dataArr.length == 6 && !"".equals(dataArr[5])) {
                    hdjsbs = dataArr[5];
                }

                JSONObject insertJson = new JSONObject();
                insertJson.put("yxpthdsqm", sqm);
                com.customization.unionpay.market.dao.MarketActivityEventDao marketActivityEventDao = new MarketActivityEventDao();
                List<JSONObject> marketActivityEventList = marketActivityEventDao.queryBySqm(Arrays.asList(new String[]{sqm}));
                if (marketActivityEventList != null && marketActivityEventList.size() > 0) {
                    JSONObject marketActivityEvent = marketActivityEventList.get(0);
                    insertJson.put("ACT_NM", Util.null2String(marketActivityEvent.getString("hdmc")));
                    insertJson.put("ACT_TOTOL_AT", marketActivityEvent.getFloatValue("ACT_TOTOL_AT"));
                    insertJson.put("jbr", Util.null2String(marketActivityEvent.getString("sqr")));
                    insertJson.put("zbdw", Util.null2String(marketActivityEvent.getString("gs")));
                } else {
                    insertJson.put("ACT_NM", "");
                    insertJson.put("ACT_TOTOL_AT", "");
                    insertJson.put("jbr", "");
                    insertJson.put("zbdw", "");
                }
                insertJson.put("ywlx", ywlx);
                //判断sqm最后一位,如果为“1”位内部营销、尾号“2”为外部营销，尾号“3”为内外部联合营销
                List<JSONObject> zjlyList = com.customization.unionpay.market.util.FormDataUtils.getItemInfo(com.customization.unionpay.market.util.FormUtil.CLEAR_FUND_DETAIL_ID,
                        "zjly", null, null);
                Map<String, String> zjlyMap = new HashMap<>();
                for (JSONObject jsonObject : zjlyList) {
                    zjlyMap.put(jsonObject.getString("name"), jsonObject.getString("value"));
                }
                if ("1".equals(sqm.substring(sqm.length() - 1))) {
                    insertJson.put("zjly", zjlyMap.getOrDefault("内部营销", "0"));
                } else if ("2".equals(sqm.substring(sqm.length() - 1))) {
                    insertJson.put("zjly", zjlyMap.getOrDefault("外部营销", "0"));
                } else if ("3".equals(sqm.substring(sqm.length() - 1))) {
                    insertJson.put("zjly", zjlyMap.getOrDefault("内外部联合营销", "0"));
                } else {
                    insertJson.put("zjly", "0");
                }
                //
                insertJson.put("ptqdrq", ptqdrq);
                insertJson.put("qsrq", qsrq);
                insertJson.put("qsje", qsje);
                insertJson.put("hdjsbs", hdjsbs);
                //判断业务类型最后一个字母是否为_,如果为_,为“营销平台手工导入”
                List<JSONObject> sjlyList = com.customization.unionpay.market.util.FormDataUtils.getItemInfo(com.customization.unionpay.market.util.FormUtil.CLEAR_FUND_DETAIL_ID,
                        "sjly", null, null);
                Map<String, String> sjlyMap = new HashMap<>();
                for (JSONObject jsonObject : sjlyList) {
                    sjlyMap.put(jsonObject.getString("name"), jsonObject.getString("value"));
                }
                if ("_".equals(ywlx.substring(ywlx.length() - 1))) {
                    //营销平台手工导入
                    insertJson.put("sjly", sjlyMap.getOrDefault("营销平台手工导入", "0"));
                } else {
                    //营销平台推送
                    insertJson.put("sjly", "0");
                }
                //状态 默认为未确认
                List<JSONObject> ztList = FormDataUtils.getItemInfo(com.customization.unionpay.market.util.FormUtil.CLEAR_FUND_DETAIL_ID,
                        "zt", null, null);
                Map<String, String> ztMap = new HashMap<>();
                for (JSONObject jsonObject : ztList) {
                    ztMap.put(jsonObject.getString("name"), jsonObject.getString("value"));
                }
                insertJson.put("zt", ztMap.getOrDefault("未确认", "0"));
                //建模ID
                insertJson.put("formmodeid", com.customization.unionpay.market.util.FormUtil.CLEAR_FUND_DETAIL_MODEL_ID);
                //创建人ID
                insertJson.put("modedatacreater", user.getUID());
                ClearFundDetailDao clearFundDetailDao = new ClearFundDetailDao();
                List<JSONObject> clearFundDetailList = clearFundDetailDao.selectByUnionKey(sqm, qsrq, ywlx);
                if (clearFundDetailList != null && clearFundDetailList.size() > 0) {
                    //已存在
                } else {
                    //不存在
                    clearFundDetailDao.insert(insertJson);

                    String zjlyValue = String.valueOf(insertJson.get("zjly"));
                    String sjlyValue = String.valueOf(insertJson.get("sjly"));
                    // 清算汇总
                    clearFundDetailsButtonService.addOrUpdateInfo(formId, formmodeId, user, ywlx, zjlyValue, qsrq, sjlyValue, qsje);
                }

            }
            //这里处理数据权限重构的问题
            FormDataUtil.permissionReset(com.customization.unionpay.market.util.FormUtil.CLEAR_FUND_DETAIL_MODEL_ID,
                    FormUtil.CLEAR_FUND_DETAIL);
        } catch (Exception e) {
            log.error("saveDate" + e, e);
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        String date = "20240406";
        String a = String.format("%s-%s-%s",
                date.substring(0, 4),
                date.substring(4, 6),
                date.substring(6, 8));
        System.out.println(a);
        String sqm = "202404063";
        if ("1".equals(sqm.substring(sqm.length() - 1))) {
            System.out.println("内部营销");
        } else if ("2".equals(sqm.substring(sqm.length() - 1))) {
            System.out.println("外部营销");
        } else if ("3".equals(sqm.substring(sqm.length() - 1))) {
            System.out.println("内外部联合营销");
        } else {
            System.out.println("其他");
        }
    }
}
